package com.xuan.yupao.service.impl;

import com.xuan.yupao.common.ErrorCode;
import com.xuan.yupao.exception.BusinessException;
import com.xuan.yupao.model.domain.Team;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.service.FileService;
import com.xuan.yupao.service.TeamService;
import com.xuan.yupao.service.UserService;
import com.xuan.yupao.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class FileServiceImpl implements FileService {

    // 最大限制上传 2M 的图片
    private static final int FILE_MAX_SIZE = 2 * 1024 * 1024;

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private FileUtils fileUtils;


    @Override
    public String uploadUserAvatar(MultipartFile file, User loginUser) {
        // 1. 检查文件大小和文件类型
        checkFileSizeAndType(file);

        // 2. 利用阿里云对象存储服务上传图片
        String avatarUrl = fileUtils.uploadImage(file);

        // 3. 修改数据库数据
        User user = new User();
        user.setId(loginUser.getId());
        user.setAvatarUrl(avatarUrl);
        boolean b = userService.updateById(user);
        if (!b) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改用户头像失败!");
        }
        return avatarUrl;
    }

    @Override
    public String uploadTeamAvatar(MultipartFile file, User loginUser, Long teamId) {
        // 1. 检查文件大小和文件类型
        checkFileSizeAndType(file);
        // 2. 查看队伍是否存在
        Team oldTeam = teamService.getById(teamId);
        if (oldTeam == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "队伍不存在");
        }
        // 3. 只有管理员或者队伍队长才有权限修改队伍的头像
        if (!userService.isAdmin(loginUser) || !Objects.equals(loginUser.getId(), oldTeam.getUserId())) {
            throw new BusinessException(ErrorCode.NOT_AUTH, "无权限");
        }
        // 4. 修改数据库数据
        String avatarUrl = fileUtils.uploadImage(file);
        Team newTeam = new Team();
        newTeam.setId(teamId);
        newTeam.setCoverImage(avatarUrl);
        boolean b = teamService.updateById(newTeam);
        if (!b) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改队伍头像失败!");
        }
        return avatarUrl;
    }


    private void checkFileSizeAndType(MultipartFile file) {
        String contentType = file.getContentType();
        long size = file.getSize();
        if (size > FILE_MAX_SIZE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件过大,请上传小于 2M 的图片");
        }
        if (contentType != null && !contentType.startsWith("image/")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "只能上传图片类型的文件");
        }
    }
}
